import os, sys, requests
from webdriver_manager.core.os_manager import OperationSystemManager
import json, time, random
from myselenium.auto_down_chromedriver import down_chromedriver_version1
from undetected_chromedriver import Chrome, ChromeOptions, find_chrome_executable
from selenium.webdriver.common.by import By


def get_options():
    options = ChromeOptions()
    options.add_argument("--disable-blink-features=AutomationControlled")
    # options.add_argument("--disable-blink-features=AutomationControlled")
    # options.add_experimental_option("excludeSwitches", ["enable-automation"])
    # options.add_experimental_option("useAutomationExtension", False)
    # options.add_experimental_option("detach", True)
    options.add_argument("--disable-extensions")
    options.add_argument("--no-default-browser-check")
    options.add_argument( "disable-dev-shm-usage")

    options.add_argument("--no-first-run")
    options.add_argument("--disable-popup-blocking")
    options.add_argument("--disable-default-apps")
    options.add_argument("--disable-infobars")
    # options.add_argument("--disable-gpu")
    # options.add_argument("--disable-notifications")
    options.add_argument("--disable-translate")
    options.add_argument("--disable-device-discovery-notifications")
    options.add_argument("--no-sandbox")
    # options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--window-size=1920x1080")
    options.add_argument("--disable-features=VizDisplayCompositor")


    return options


def getchromeversion():
    if 'win' in sys.platform:
        import winreg
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Google\Chrome\BLBeacon')
        chrome_version = winreg.QueryValueEx(key, 'version')[0]
        return chrome_version
    else:
        osm = OperationSystemManager()
        browserVersion = osm.get_browser_version_from_os("google-chrome")
        print(f'Chrome version is {browserVersion}')
        mainBrowserVersion = browserVersion.split(".")[0]  # 获取chrome浏览器的主版本号
        return browserVersion


def cmd_start_brower(chrome_path, port, user_data_dir):
    # current_file_path = os.path.dirname(os.path.realpath(sys.argv[0]))
    # user_data_dir = os.path.join(current_file_path, "pyppeteer_chrome")  # 浏览器用户配置文件
    chrome_path_temp = chrome_path.replace('\chrome.exe', '')
    start_params = f'cd {chrome_path} && chrome.exe --remote-debugging-port={port} --user-data-dir="{user_data_dir}" --no-first-run --disable-popup-blocking --allow-file-access-from-files --no-default-browser-check'
    os.popen(start_params.format(chrome_path_temp, port, user_data_dir))


def get_session_url(chrome_path, port, user_data_dir):
    url = f'http://127.0.0.1:{port}/json/version'
    try:
        res = requests.get(url)
        print("已打开",res.text)
        webSocketDebuggerUrl = json.loads(res.text)['webSocketDebuggerUrl']

    except:
        # 命令行启动
        print("未打开", chrome_path,port,user_data_dir)
        cmd_start_brower(chrome_path, port, user_data_dir)
        time.sleep(random.randint(4, 6))




user_data_name = "userdata"
port = 9315
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
current_path = os.path.dirname(os.path.realpath(sys.argv[0]))
# 浏览器用户配置文件
user_data_dir = "E:\\userdata"
if not os.path.exists(user_data_dir):
    os.mkdir(user_data_dir)

# 浏览器版本号
# version = getchromeversion().split('.')[0]
version="112"

# 下载驱动
chromedriverpath = down_chromedriver_version1(path=".\\", version=version)
chrome_path = find_chrome_executable()
# 检测浏览器是否已打开
get_session_url(chrome_path, port, user_data_dir)
option = get_options()
option.add_argument(fr'--user-data-dir="{user_data_dir}"')
option.add_argument(f"--user-agent={user_agent}")
option.debugger_address = f"127.0.0.1:{port}"
browser_executable_path=r"F:\chrome\Chrome-bin\\chrome.exe"
executable_path=r"D:\code\my-mitmproxy\myselenium\chromedriver\chromedriver_112.exe"

driver = Chrome(options=option,browser_executable_path=browser_executable_path, executable_path=executable_path, use_subprocess=True)
print(driver.title)

def start_brower():
    pass
    driver.get('https://blog.csdn.net/lwdfzr/article/details/135410359')
    time.sleep(random.randint(3, 5))
    try:
        driver.find_element(By.ID,"kw").send_keys("自动化")
    except:
        pass
    print("执行结束...")
    time.sleep(2)



if __name__ == '__main__':
    start_brower()


